#!/usr/bin/env python
#
# Copyright 2010 Lead Bulb, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import sys, os, shutil

DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
PROJECT_TEMPLATE_DIR = os.path.join(DIR_PATH, 'new_project_template')

def startproject(directory):
	'''
		def startproject
		@param Str	directory Application Directory to create new project in
		@return Int	sys.exit status
	'''

	# See if project directory exists, if so we don't want to make it there
	if os.path.exists(directory):
		print >>sys.stderr, "Error: Directory %s already exists.\n" % directory
		return 1

	# Make new project directory
	try:
		os.mkdir(directory)
	except OSError, e:
		print >>sys.stderr, "Error: %s\n" % e;
		return 1

	# Go through all files in our default project directory and copy them
	# TODO: Make this go through subdirs too
	for d, subdirs, files in os.walk(PROJECT_TEMPLATE_DIR):
		relative_dir = d[len(PROJECT_TEMPLATE_DIR)+1:]
		if relative_dir:
			if relative_dir.startswith('.'):
				continue

			os.mkdir(os.path.join(directory, relative_dir))

		for f in files:
			if f.endswith('.pyc') or f.endswith('.py~'): # Don't crap any compiled or backup files
				continue
			if f.startswith('.'): # Don't copy hidden stuff (like SVN entries)
				continue

			path_old = os.path.join(d, f)
			path_new = os.path.join(directory, relative_dir, f)
			fp_old = open(path_old, 'r')
			fp_new = open(path_new, 'w')
			fp_new.write(fp_old.read())
			fp_old.close()
			fp_new.close()
			try:
				shutil.copymode(path_old, path_new)
			except OSError:
				print >>sys.stderr, "Notice: Couldn't set permission bits on %s. You're probably using an uncommon filesystem setup. No problem.\n" % path_new
	return 0
